package com.whfc.wxmp.config;

import com.whfc.common.util.SessionAttr;
import com.whfc.fuum.entity.SysUser;
import com.whfc.fuum.entity.WxUser;
import com.whfc.wxmp.jwt.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: sun
 * @version: v1.0.0
 * @since 2022/7/26
 */
public abstract class AbstractBaseController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private HttpServletRequest request;

    protected WxUser getLoginUser(HttpServletRequest request) {
        WxUser wxUser = getMsLoginUser(request);
        if (wxUser != null) {
            return wxUser;
        }
        Session session = SecurityUtils.getSubject().getSession();
        return (WxUser) session.getAttribute(SessionAttr.WXMP_USER);
    }

    protected Integer getUserId() {
        Integer userId = null;
        WxUser wxUser = getMsLoginUser(request);
        if (wxUser != null) {
            return wxUser.getId();
        }
        try {
            Session session = SecurityUtils.getSubject().getSession();
            SysUser user = (SysUser) session.getAttribute(SessionAttr.MS_USER);
            if (user != null) {
                userId = user.getId();
            }
        } catch (Exception e) {
            logger.error("获取用户ID出错:" + e.getMessage(), e);
        }
        return userId;
    }

    private WxUser getMsLoginUser(HttpServletRequest request) {
        // 1. 优先从JWT获取
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            try {
                String token = authHeader.substring(7);
                Claims claims = JwtUtil.parseToken(token);
                WxUser wxUser = new WxUser();
                Object id = claims.get("id");
                if (id instanceof Integer) {
                    wxUser.setId((Integer) id);
                } else if (id != null) {
                    wxUser.setId(Integer.parseInt(id.toString()));
                }
                wxUser.setPhone((String) claims.get("phone"));
                wxUser.setName((String) claims.get("name"));
                wxUser.setOpenId((String) claims.get("openId"));
                Object appType = claims.get("appType");
                if (appType instanceof Integer) {
                    wxUser.setAppType((Integer) appType);
                } else if (appType != null) {
                    wxUser.setAppType(Integer.parseInt(appType.toString()));
                }
                return wxUser;
            } catch (Exception e) {
                logger.warn("JWT解析失败，尝试从Session获取用户", e);
                return null;
            }
        }
        return null;
    }
}
